<template>
    <div class="user-manager">
        <div class="query-form">    
            <!-- 查询区域 -->
            <el-form ref="form" :inline="true" :model="user">
                <el-form-item label="用户ID" prop="userId">
                    <el-input v-model="user.userId" placeholder="请输入用户ID"/>
                </el-form-item>
                <el-form-item label="用户名称" prop="userName">
                    <el-input v-model="user.userName" placeholder="请输入用户名称"/>
                </el-form-item>
                <el-form-item label="状态" prop="state">
                    <el-select v-model="user.state" class="el-select" style="width: 100px;">
                        <el-option :value="0"  label="所有" />
                        <el-option :value="1"  label="正常" />
                        <el-option :value="2"  label="禁用" />
                        <el-option :value="3" label="待审核" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleQuery">查询</el-button>
                    <el-button @click="handleReset('form')">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="base-table">
            <!-- 列表区域 -->
            <div class="action">
                <el-button type="primary" @click="handleCreate" v-has:add="'user-create'">新增用户</el-button>
                <el-button type="danger" @click="handlePatchDel" v-has="'user-patch-delete'">批量禁用</el-button>
            </div>
            <el-table :data="userList" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column
                    v-for="item in columns"
                    :key="item.prop"
                    :prop="item.prop" 
                    :label="item.label" 
                    :width="item.width"
                    :formatter="item.formatter"
                    align="center"
                >
                </el-table-column>
                <el-table-column label="操作" min-width="220">
                    <template #default="scope">
                        <el-button type="primary" size="small" @click="handleEdit(scope.row)" v-has="'user-edit'">编辑</el-button>
                        <el-button type="danger" size="small" @click="handleDel(scope.row)" v-has="'user-delete'">
                            {{ scope.row.state === 2 ? '启用' : '禁用' }}
                        </el-button>
                        <el-button size="small" @click="handlePwdReset(scope.row)" v-has="'user-reset'">重置密码</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination 
                class="pagination"
                background
                layout="prev, pager, next" 
                :total="pager.total || 1"
                :page-size="pager.pageSize"
                @current-change="handleCurrentChange"
            />
        </div>
        <el-dialog :title="action=='add'?'新增用户':'编辑用户'" v-model="showModel" width="40%" class="user-dialog" @close="handleClose">
            <el-form ref="dialogForm" :model="userForm" label-width="70px" class="compact-form" :rules="rules">
                <el-form-item label="用户名" prop="userName">
                    <el-input v-model="userForm.userName" :disabled="action == 'edit'" placeholder="请输入用户名称"/>
                </el-form-item>
                <el-form-item label="邮箱" prop="userEmail">
                    <el-input v-model="userForm.userEmail" :disabled="action == 'edit'" placeholder="请输入邮箱地址"/>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="userForm.mobile" placeholder="请输入手机号"/>
                </el-form-item>
                <el-form-item label="状态" prop="state">
                    <el-select v-model="userForm.state">
                        <el-option :value="1" label="正常"></el-option>
                        <el-option :value="2" label="禁用"></el-option>
                        <el-option :value="3" label="待审核"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="用户角色" prop="roleList">
                    <el-select v-model="userForm.roleList" placeholder="请选择用户角色" multiple style="width: 100%;">
                        <el-option 
                        v-for="role in roleList" 
                        :key="role._id" 
                        :label="role.roleName"
                        :value="role._id"
                        ></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="handleClose">取消</el-button>
                        <el-button type="primary" @click="handleSubmit">确定</el-button>
                    </div>
                </template>
        </el-dialog>
    </div>
</template>
  
<script>
import { getCurrentInstance, onMounted, reactive, ref, toRaw } from 'vue'
import utils from '@/utils/utils.js'
export default {
    name:'UserManager',
    setup(){
        // 获取composition api的全局对象
        const { proxy  } = getCurrentInstance();
        // 初始化用户表单对象
        const user = reactive({
            state: 1
        });
        // 初始化用户列表数据
        const userList = ref([]);
        // 初始化分页对象
        const pager = reactive({
            pageNum: 1,
            pageSize: 10,
        })
        // 选中用户列表的对象
        const checkedUserIds = ref([])
        // 弹框显示对象
        const showModel = ref(false);
        // 新增用户Form对象
        const userForm = reactive({
            state: 3, // 默认待审核状态
        })
        // 所有角色列表
        const roleList = ref([]);
        // 定义用户操作的行为
        const action = ref('add')
        // 定义表单验证规则
        const rules = reactive({
            userName: [
                { 
                    required: true, 
                    message: '请输入用户名', 
                    trigger: 'blur' 
                }
            ],
            userEmail: [
                {   
                    required: true, 
                    message: '请输入邮箱地址', 
                    trigger: 'blur' 
                },
                {
                    type: 'email',
                    message: '请输入正确的邮箱格式',
                    trigger: ['blur', 'change']
                }
            ],
            // 正则表达式验证手机号格式
            mobile: [
                {
                    pattern: /1[3-9]\d{9}/, 
                    message: '请输入正确的手机号格式', 
                    trigger: 'blur' 
                }
            ]
        })
        // 定义动态表格-格式
        const columns = reactive([
            {
                label:'用户ID',
                prop: 'userId',
                width: 100
            },
            {
                label:'用户名',
                prop: 'userName',
                width: 100
            },
            {
                label:'用户邮箱',
                prop: 'userEmail',
                width: 160
            },
            {
                label:'手机号',
                prop: 'mobile',
                width: 120
            },
            {
                label:'用户角色',
                prop:'role',
                formatter(row, column, value){
                    return {
                        0: '系统管理员',
                        1: '普通用户'
                    }[value]
                },
                width: 120
            },
            {
                label:'用户状态',
                prop:'state',
                formatter(row, column, value){
                    return {
                        1: '正常',
                        2: '禁用',
                        3: '待审核'
                    }[value]
                },
                width: 120
            },
            {
                label:'注册时间',
                prop: 'createTime',
                width: 200,
                formatter: (row, column, value) => {
                    return utils.formateDate(new Date(value))
                }
            },
            {
                label:'最后登录',
                prop: 'lastLoginTime',
                width: 200,
                formatter: (row, column, value) => {
                    return utils.formateDate(new Date(value))
                }
            }
        ])
        // 初始化接口调用
        onMounted(() => {
            getUserList();
            getRoleAllList();
        })
        // 获取用户列表
        const getUserList = async ()=>{
            let params = { ...user, ...pager };
            try {
                const { list, page } = await proxy.$api.getUserList(params);
                userList.value = list;
                pager.total = page.total;
            } catch (error) {}
        }
        // 查询事件，获取用户列表
        const handleQuery = ()=>{
            getUserList();
        }
        // 重置查询表单
        const handleReset = (form)=>{
            proxy.$refs[form].resetFields();
        }
        // 分页事件处理
        const handleCurrentChange = (current)=>{
            pager.pageNum = current;
            getUserList();
        }
        // 用户单个禁用/启用
        // const handleDel = async (row)=>{
        //     // 切换状态：正常→禁用，禁用→正常
        //     const newState = row.state === 2 ? 1 : 2;
        //     await proxy.$api.userDel({
        //         userIds: [row.userId]
        //     })
        //     proxy.$message.success(newState === 2 ? '禁用成功' : '启用成功');
        //     getUserList();
        // }
        const handleDel = async (row) => {
            const newState = row.state === 2 ? 1 : 2;
            try {
                // 调用接口后，返回的是后端的 data 字段（即 { modifiedCount: 1 }）
                const response = await proxy.$api.updateUserState({
                userId: row.userId,
                state: newState
                });

                // 关键：通过 modifiedCount 判断是否成功（修改了1条数据就是成功）
                if (response && response.modifiedCount >= 1) {
                const tip = newState === 2 ? '禁用成功' : '启用成功';
                proxy.$message.success(tip);
                getUserList(); // 立即刷新列表，不用手动刷新
                } else {
                const tip = newState === 2 ? '禁用失败' : '启用失败';
                proxy.$message.error(tip);
                }
            } catch (error) {
                proxy.$message.error('操作失败：' + (error.message || '网络异常'));
            }
        }   
        // 批量禁用
        // const handlePatchDel = async ()=>{
        //     if(checkedUserIds.value.length == 0){
        //         proxy.$message.error('请选择要操作的用户');
        //         return;
        //     }
        //     const res = await proxy.$api.userDel({
        //         userIds: checkedUserIds.value
        //     })
        //     if(res.modifiedCount > 0){
        //         proxy.$message.success('批量操作成功');
        //         getUserList();
        //     }else{
        //         proxy.$message.error('操作失败');
        //     }
        // }
        const handlePatchDel = async () => {
            if (checkedUserIds.value.length === 0) {
                proxy.$message.error('请选择要操作的用户');
                return;
            }

            const firstUser = userList.value.find(u => checkedUserIds.value.includes(u.userId));
            const newState = firstUser.state === 2 ? 1 : 2;

            try {
                const response = await proxy.$api.batchUpdateUserState({
                userIds: checkedUserIds.value,
                state: newState
                });

                // 同样通过 modifiedCount 判断
                if (response && response.modifiedCount >= 1) {
                const tip = newState === 2 ? '批量禁用成功' : '批量启用成功';
                proxy.$message.success(tip);
                getUserList(); // 立即刷新列表
                } else {
                const tip = newState === 2 ? '批量禁用失败' : '批量启用失败';
                proxy.$message.error(tip);
                }
            } catch (error) {
                proxy.$message.error('操作失败：' + (error.message || '网络异常'));
            }
        }
        // 用户重置密码
        const handlePwdReset = async (row)=>{
            await proxy.$api.userPwdReset({
                userIds: [row.userId]
            })
            proxy.$message.success('密码重置成功，默认密码：123456');
        }    
        // 表格多选
        const handleSelectionChange = (list) => {
            // 选中用户列表
            let arr = [];
            list.map(item=>{
                arr.push(item.userId);
            })
            checkedUserIds.value = arr;
        }
        // 用户新增
        const handleCreate = () => {
            // 设置操作类型
            action.value = 'add';
            // 清空表单
            Object.assign(userForm, {
                userName: '',
                userEmail: '',
                mobile: '',
                job: '',
                state: 3,
                roleList: []
            });
            // 显示弹框
            showModel.value = true;
        }
        // 角色列表查询
        const getRoleAllList = async () => {
            // 调用接口，获取所有角色列表
            let list = await proxy.$api.getRoleAllList()
            // 将获取的数据赋值给组件
            roleList.value = list;
        }
        // 用户弹窗关闭
        const handleClose = ()=>{
            showModel.value = false;
            handleReset('dialogForm');
        }
        // 用户新增或编辑提交
        const handleSubmit = () => {
            // 表单验证
            proxy.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                    // 获取表单数据
                    let params = toRaw(userForm);
                    params.action = action.value;
                    // 调用接口，提交数据
                    await proxy.$api.userSubmit(params);
                    showModel.value = false;
                    proxy.$message.success(action.value === 'edit' ? '用户编辑成功' : '用户创建成功');
                    handleReset('dialogForm');
                    getUserList();
                }
            });
        }
        // 用户编辑 
        const handleEdit = async (row) => {
            action.value = "edit";
            showModel.value = true;
            proxy.$nextTick(() => {
                // 复制行数据到表单
                Object.assign(userForm, {
                    userId: row.userId,
                    userName: row.userName,
                    userEmail: row.userEmail,
                    mobile: row.mobile,
                    job: row.job,
                    state: row.state,
                    roleList: row.roleList
                });
            })
        }
        // 暴露变量和方法
        return {
            user,
            userList,
            columns,
            pager,
            checkedUserIds,
            showModel,
            userForm,
            rules,
            roleList,
            action,
            getUserList,
            handleQuery,
            handleReset,
            handleCurrentChange,
            handleDel,
            handlePatchDel,
            handleSelectionChange,
            handleCreate,
            getRoleAllList,
            handleClose,
            handleSubmit,
            handleEdit,
            handlePwdReset
        }
    }
}
</script>
  
  
  
<style lang="scss">
.user-manager{
    .query-form{
        background-color: #ffffff;
        padding: 22px 20px 0;
        border-radius: 5px;
        .el-select{
            width: 80px;
        }
    }
    .base-table{
        border-radius: 5px 5px 0px 0px;
        background: #ffffff;
        padding: 20px;
        border-bottom: 1px solid #e4e8e8;
        .action {
            margin-bottom: 15px;
        }
        .pagination{
            margin-top: 20px;
            display: flex;
            justify-content: flex-end; /* 靠右对齐 */
        }
    }
    .user-dialog {
        .el-dialog__body {
            padding: 20px 25px 10px;  // 上 左右 下
        }
        .compact-form {
            .el-form-item {
                margin-bottom: 16px;
                
                .el-form-item__label {
                padding-right: 12px;
                color: #606266;
                }
                
                .el-input, .el-select {
                    width: 100%;
                }
            }
        }
        .dialog-footer {
            display: flex;
            justify-content: flex-end;
            padding: 10px 20px 20px;
            .el-button {
                min-width: 80px;
                margin-left: 12px;
            }
        }
    }
}
</style>
